package cloud.agileframework.dictionary;

import cloud.agileframework.common.constant.Constant;
import cloud.agileframework.common.util.object.ObjectUtil;
import cloud.agileframework.dictionary.cache.DictionaryCache;
import cloud.agileframework.dictionary.cache.MemoryCacheImpl;
import cloud.agileframework.dictionary.util.DictionaryUtil;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 佟盟
 * 日期 2020/8/3 15:35
 * 描述 内存字典数据管理器
 * @version 1.0
 * @since 1.0
 */
public class MemoryDictionaryManager implements DictionaryDataManager<DictionaryDataBase> {
    /**
     * 字典数据缓存
     */
    private static final Map<String, DictionaryDataBase> CACHE = Maps.newConcurrentMap();

    public static Set<DictionaryDataBase> store() {
        return new HashSet<>(CACHE.values());
    }

    @Override
    public List<DictionaryDataBase> all() {
        return new ArrayList<>(CACHE.values());
    }

    @Override
    public String dataSource() {
        return Constant.AgileAbout.DIC_DATASOURCE;
    }

    public DictionaryDataBase add(DictionaryDataBase dictionaryDataBase) {
        CACHE.put(dictionaryDataBase.getId(),dictionaryDataBase);
        refresh();
        return DictionaryUtil.findById(dataSource(),dictionaryDataBase.getId());
    }

    public void delete(DictionaryDataBase dictionaryDataBase) {
        CACHE.remove(dictionaryDataBase.getId());
        refresh();
    }

    public DictionaryDataBase update(DictionaryDataBase dictionaryDataBase) {
        delete(dictionaryDataBase);
        add(dictionaryDataBase);
        refresh();
        return DictionaryUtil.findById(dataSource(),dictionaryDataBase.getId());
    }

    public DictionaryDataBase updateOfNotNull(DictionaryDataBase dictionaryDataBase) {
        DictionaryDataBase dic = DictionaryUtil.findById(dataSource(), dictionaryDataBase.getId());
        ObjectUtil.copyProperties(dictionaryDataBase, dic, ObjectUtil.Compare.DIFF_SOURCE_NOT_NULL);
        update(dic);
        refresh();
        return DictionaryUtil.findById(dataSource(),dictionaryDataBase.getId());
    }

    @Override
    public DictionaryCache cache() {
        return MemoryCacheImpl.INSTANT;
    }
}
